package com.xiaobai.mall.index.web.interceptor;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.xiaobai.mall.cache.ICache;
import com.xiaobai.mall.common.exception.SessionException;
import com.xiaobai.mall.index.domain.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Optional;

public class SessionInterceptor implements HandlerInterceptor {

    @Resource
    ICache cache;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String session = Arrays.stream(Optional.ofNullable(request.getCookies()).orElseGet(() -> new Cookie[]{})).filter(cookie -> "sessionId".equals(cookie.getName())).findFirst().map(Cookie::getValue).orElse(null);
        if (StrUtil.isEmpty(session)) {
            session = request.getHeader("sessionId");
        }
        Assert.notBlank(session, () -> new SessionException("未登录"));
        User user = cache.get(session);
        Assert.notNull(user, () -> new SessionException("未登录"));
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
